package com.deyou.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.deyou.Constants;
import com.deyou.R;
import com.deyou.adapter.HouseResourceItemAdapter;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.HouseResourceAttrBean;
import com.deyou.model.LzyResponse;
import com.deyou.model.OrderBean;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.deyou.R.id.viewpager;

public class HouseResourceListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.tv_tab_one)
    TextView tvTabOne;
    @BindView(R.id.tab_line_one)
    View tabLineOne;
    @BindView(R.id.tab_one_layout)
    RelativeLayout tabOneLayout;
    @BindView(R.id.tv_tab_two)
    TextView tvTabTwo;
    @BindView(R.id.tab_line_two)
    View tabLineTwo;
    @BindView(R.id.tab_two_layout)
    RelativeLayout tabTwoLayout;
    @BindView(R.id.tv_tab_three)
    TextView tvTabThree;
    @BindView(R.id.tab_line_three)
    View tabLineThree;
    @BindView(R.id.tab_three_layout)
    RelativeLayout tabThreeLayout;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.tv_tab_four)
    TextView tvTabFour;
    @BindView(R.id.tab_line_four)
    View tabLineFour;
    @BindView(R.id.tab_four_layout)
    RelativeLayout tabFourLayout;
    @BindView(R.id.status_view)
    LinearLayout statusView;

    private HouseResourceItemAdapter mAdapter;
    private boolean isRefresh = false;
    private String resourceStatus = "1,2,3,";
    private List<HouseResourceAttrBean> houseList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_resource_list);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected boolean translucentStatusBar() {
        return super.translucentStatusBar();
    }

    private void initView() {
        tvMidTitle.setText("我的房源");

        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));
        mAdapter = new HouseResourceItemAdapter(this);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(true);
        mAdapter.setOnItemClickListener(this);
        refreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        refreshLayout.setOnRefreshListener(this);
        recyclerView.setAdapter(mAdapter);
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    @OnClick({R.id.iv_left_back, R.id.tab_one_layout, R.id.tab_two_layout, R.id.tab_three_layout, R.id.tab_four_layout, R.id.add_house_view})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.tab_one_layout:
                dealStatusTitle(1);
                break;
            case R.id.tab_two_layout:
                dealStatusTitle(2);
                break;
            case R.id.tab_three_layout:
                dealStatusTitle(3);
                break;
//            case R.id.tab_four_layout:
//                dealStatusTitle(4);
//                break;
            case R.id.add_house_view:
                AndroidUtils.startNextActivity(HouseResourceListActivity.this, HouseTypeActivity.class, null, false);
                break;
        }
    }

    @Override
    public void onRefresh() {
        setRefreshing(false);
        searchHouseResource(resourceStatus);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        houseList = (List<HouseResourceAttrBean>)adapter.getData();
        if (null == houseList || houseList.size() == 0 || houseList.get(position) == null)
            return;
        Bundle bundle = new Bundle();
        bundle.putString("resourceCode", houseList.get(position).resourceId);
        AndroidUtils.startNextActivity(HouseResourceListActivity.this, HouseResourceDetailActivity.class, bundle, false);
    }

    @Override
    public void onLoadMoreRequested() {

    }

    private void dealStatusTitle(int status) {
        setRefreshing(true);
        onRefresh();
        tabLineOne.setVisibility(View.GONE);
        tvTabOne.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineTwo.setVisibility(View.GONE);
        tvTabTwo.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineThree.setVisibility(View.GONE);
        tvTabThree.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineFour.setVisibility(View.GONE);
        tvTabFour.setTextColor(getResources().getColor(R.color.color_272424));
        switch (status) {
            case 1:
                tabLineOne.setVisibility(View.VISIBLE);
                tvTabOne.setTextColor(getResources().getColor(R.color.color_FF832D));
                resourceStatus = "1,2,3,";
                break;
            case 2:
                tabLineTwo.setVisibility(View.VISIBLE);
                tvTabTwo.setTextColor(getResources().getColor(R.color.color_FF832D));
                resourceStatus = "2,";
                break;
            case 3:
                tabLineThree.setVisibility(View.VISIBLE);
                tvTabThree.setTextColor(getResources().getColor(R.color.color_FF832D));
                resourceStatus = "3,";
                break;
            case 4:
                tabLineFour.setVisibility(View.VISIBLE);
                tvTabFour.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
        }
        setRefreshing(true);
        onRefresh();
    }

    private void searchHouseResource(String status) {
        JSONObject object = new JSONObject();
        try {
            object.put("myuserId", SPUtils.getStringByKey(HouseResourceListActivity.this, Constants.UserId));
            object.put("resourceStatus", status);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String paramJson = object.toString();

        Type type = new TypeToken<LzyResponse<HouseResourceAttrBean>>() {}.getType();
        ServerApi.<LzyResponse<HouseResourceAttrBean>>getData(type, Urls.searchHouseResource, "", AESUtil.encrypt(paramJson))//
                .subscribeOn(Schedulers.io())//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        showLoading();
                    }
                })//
                .map(new Function<LzyResponse<HouseResourceAttrBean>, HouseResourceAttrBean>() {
                    @Override
                    public HouseResourceAttrBean apply(@NonNull LzyResponse<HouseResourceAttrBean> response) throws Exception {
                        return response.data;
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())  //
                .subscribe(new Observer<HouseResourceAttrBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull HouseResourceAttrBean houseResourceBean) {
                        if (isRefresh)
                            setRefreshing(false);
                        else
                            dismissLoading();
                        if (null != houseResourceBean) {
                            if (null != houseResourceBean.content && houseResourceBean.content.size() > 0) {
                                if (houseResourceBean.first)
                                    mAdapter.setNewData(houseResourceBean.content);
                                else
                                    mAdapter.addData(houseResourceBean.content);
                            } else {
//                                List<HouseResourceAttrBean> attrBean = new ArrayList<HouseResourceAttrBean>();
//                                for (int i = 0; i < 10; i++){
//                                    attrBean.add(new HouseResourceAttrBean());
//                                }
                                mAdapter.setNewData(null);
                            }
                            mAdapter.setEnableLoadMore(!houseResourceBean.last);
                        } else {
//                            List<HouseResourceAttrBean> attrBean = new ArrayList<HouseResourceAttrBean>();
//                            for (int i = 0; i < 10; i++){
//                                attrBean.add(new HouseResourceAttrBean());
//                            }
                            mAdapter.setNewData(null);
//                            mAdapter.setEnableLoadMore(false);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();            //请求失败
                        if (isRefresh)
                            setRefreshing(false);
                        else
                            dismissLoading();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        setRefreshing(true);
        onRefresh();
    }
}
